#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int main()
{
    vector<int> enter_queue = {5, 8, 1, 7, 4, 2, 9, 6, 3};
    int enter_size = enter_queue.size();
    queue<int> buffer01;
    queue<int> buffer02;
    queue<int> buffer03;
    vector<queue<int>>buffer {buffer01, buffer02, buffer03};
    int newOut = 1;
    while (newOut != 10)
    {
        if (enter_queue.back() == newOut)
        {
            cout << enter_queue.back() << endl;
            enter_queue.pop_back();
            newOut++;
        }
        for (int j = 0; j < 3; j++)
        {
            if (!buffer[j].empty() && buffer[j].front() == newOut)
                {
                    cout << buffer[j].front() << endl;
                    buffer[j].pop();
                    newOut++;
                    continue;
                }
        }
        for (int j = 0; j < 3; j++)
        {
            if (buffer[j].empty() || enter_queue.back() > buffer[j].front() && buffer[j].size() != 3)
            {
//                cout << enter_queue.back() << endl;
                buffer[j].push(enter_queue.back());
                enter_queue.pop_back();
                break;
            }
        }
    }
    return 0;
}
